<?php
require_once("includes/pagetop.php");

$msg_error="";

if(isset($_FILES['resumefile']['name']) && $_FILES['resumefile']['name']!="")
{
    if(!isset($_SESSION['Allyfolio_User_ID']))
    {
        $msg_error="You should be logged in to apply for post. Please login first & then apply for post.";
        
    }
    else
    {
        $filename="";
	
        if($_FILES['resumefile']['type']=="application/kswps")
        {
            list($width, $height) = getimagesize($_FILES['resumefile']["tmp_name"]);
            $folder_val="uploads/postresume";
            if(!file_exists($folder_val))
            {
				mkdir($folder_val,0777);
			}
            $folder_val=$folder_val."/";
            
            $newfilename="";
            
            $newfilename=$_FILES['resumefile']['name'];
            $path=$folder_val.$newfilename;
            
            if(file_exists($path))
            {
				$filenamearr=explode(".",$newfilename);
                
                $newfilename="";
                
                for($i=0;$i<count($filenamearr)-1;$i++)
                {
                    $newfilename=$newfilename.$filenamearr[$i].".";
                }
                $newfilename=substr($newfilename,0,strlen($newfilename)-1);
                $newfilename=$newfilename."_".time().".".$filenamearr[count($filenamearr)-1];
                $path=$folder_val.$newfilename;
			}
            
            $move= move_uploaded_file($_FILES['resumefile']['tmp_name'], $path);
            if($move)
            {
                $filename=$newfilename;
            }
            
        }
		else
		{
			$msg_error="Resume file extension should be doc or docx.";
		}    
        
        if($msg_error=="")
        {
            $jobdetailsqry="select * from af_career_postapplications where id=:jobid";
            $jobdetails=$pdodbobj->fetch_array($pdodbobj->query($jobdetailsqry,array(":jobid"=>$_POST["Job"]["job_id"])));
            if(count($jobdetails)>0)
            {
                $msg_error="You have already applied for this job.";
            }
            else
            {
                $insertarr=array("user_id"=>$_SESSION['Allyfolio_User_ID']);
                $insertarr["careerpost_id"]=$_POST['Job']['job_id'];
                $insertarr["applied_date"]=time();
                $insertarr["resume_url"]=$filename;
                $insertarr=sanitize($insertarr);
                
                require_once"includes/mailscript.php";
                
                $subject="Allyfolio job status.";
                
                $jobdetailsqry="select * from af_careers where id=:jobid";
                $jobdetails=$pdodbobj->fetch_array($pdodbobj->query($jobdetailsqry,array(":jobid"=>$_POST["Job"]["job_id"])));
        
                $message="
                <table cellspacing='2' cellpadding='2' width='100%'>
                    <tr>
                        <td>
                        Hi ".$loggedinuserdetails[0]['Full_Name'].",<br/><br></td>
                    </tr>
                    <tr>
                        <td>
                            You have successfully applied for the post : ".$jobdetails[0]['post_name']."
                         </td>
                    </tr>
                    <tr>
                        <td>
                            Our HR Team member will contact you soon after review your resume.
                        </td>    
                    </tr>
                    <tr>
                        <td>
                        <br/>
                        <br/>
                           Thanks,<br/>Allyfolio HR Team.
                        </td>
                    </tr>       
                </table>" ;  
                
                $pdodbobj->insertData("af_career_postapplications",$insertarr);
                if($pdodbobj->affectedrows>0)
                {
                    if(sendMail($loggedinuserdetails[0]['Email_ID'],$subject,$message,$headers))
                    {
                        $msg_error="You have successfully applied for this job.";
                    }
                    
                }
            }
        }
    }
}



?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>AllyFolio | SignUp </title>
<link href="css/style.css" rel="stylesheet" type="text/css" media="all"  />

<script src="js/general.js"></script>

<link rel="stylesheet" href="alertify/themes/alertify.core.css" />
<link rel="stylesheet" href="alertify/themes/alertify.default.css" id="toggleCSS" />
<script src="alertify/lib/alertify.min.js"></script>	
<script src="js/jquery1.10.2.min.js"></script>
<script type="text/javascript" src="js/jquery.form.min.js"></script>
<script>
//<![CDATA[

$(document).ready(function() { 
    
    $(".drop_btn").click(function(){
        $(".showbox").toggle();
  });
  
  /*
	var progressbox     = $('#progressbox');
	var progressbar     = $('#progressbar');
	var statustxt       = $('#statustxt');
	var completed       = '0%';
	
	var options = { 
			target:   '#output',   // target element(s) to be updated with server response 
			beforeSubmit:  beforeSubmit,  // pre-submit callback 
			uploadProgress: OnProgress,
			success:       afterSuccess,  // post-submit callback 
			resetForm: true        // reset the form after successful submit 
		}; 
		
	 $('#sendresumebtn').click(function() { 
			$(this).ajaxSubmit(options);  			
			// return false to prevent standard browser submit and page navigation 
			return false; 
		});
*/
	
//when upload progresses	
function OnProgress(event, position, total, percentComplete)
{
	//Progress bar
	progressbar.width(percentComplete + '%') //update progressbar percent complete
	statustxt.html(percentComplete + '%'); //update status text
	if(percentComplete>50)
		{
			statustxt.css('color','#fff'); //change status text to white after 50%
		}
}

//after succesful upload
function afterSuccess()
{
	$('#submit-btn').show(); //hide submit button
	$('#loading-img').hide(); //hide submit button
    if($('#output').html()!="")
    {
        alertify.alert($('#output').html());
    }
    $('#output').html("");
}

//function to check file size before uploading.
function beforeSubmit(){
    //check whether browser fully supports all File API
   if (window.File && window.FileReader && window.FileList && window.Blob)
	{

		if( !$('#resume').val()) //check empty input filed
		{
			//$("#output").html("Are you kidding me?");
			return false
		}
		
		var fsize = $('#resume')[0].files[0].size; //get file size
		var ftype = $('#resume')[0].files[0].type; // get file type
		
		//allow only valid image file types 
		switch(ftype)
        {
            case 'application/kswps':
                break;
            default:
                $("#output").html("Resume file extension should be doc or docx.");
                //$("#output").html("<b>"+ftype+"</b> Unsupported file type!");
				return false
        }
		
		//Allowed file size is less than 1 MB (1048576)
		if(fsize>2096576) 
		{
		    $("#output").html("Max. 2 MB size resume is allowed to upload.");
            
			//$("#output").html("<b>"+bytesToSize(fsize) +"</b> Too big Image file! <br />Please reduce the size of your photo using an image editor.");
			return false
		}
		
		//Progress bar
		progressbox.show(); //show progressbar
		progressbar.width(completed); //initial value 0% of progressbar
		statustxt.html(completed); //set status text
		statustxt.css('color','#000'); //initial color of status text

				
		$('#submit-btn').hide(); //hide submit button
		$('#loading-img').show(); //hide submit button
		//$("#output").html("");  
	}
	else
	{
		//Output error to older unsupported browsers that doesn't support HTML5 File API
		$("#output").html("Please upgrade your browser, because your current browser lacks some new features we need!");
		return false;
	}
}

//function to format bites bit.ly/19yoIPO
function bytesToSize(bytes) {
   var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
   if (bytes == 0) return '0 Bytes';
   var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
   return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
}

}); 

//]]>
</script>
</head>

<body>

	<div id="main_wrapper">
    <?php
    $pageheading="Careers";
    require_once("includes/header.php");
    
    if(!isset($Job["job_id"]) || $Job["job_id"]<=0 || $Job["job_id"]=="")
    {
        redirect("careers.php");
    }
    
    $jobdetailsqry="select * from af_careers where id=:jobid";
    $jobdetails=$pdodbobj->fetch_array($pdodbobj->query($jobdetailsqry,array(":jobid"=>$_POST["Job"]["job_id"])));
    
    if(count($jobdetails)==0)
    {
        redirect("careers.php");
    }
    ?>
    <!--=================Body Contain Start=======================-->
    <div class="wrapper">
    	<div class="header">
        	        	<div class="contain-wrap">
							<div class="c2">
								<?php echo $jobdetails[0]['post_name'] ?>
							</div>
							<div>
                                <?php
                                echo $jobdetails[0]['post_description'];
                                ?>
                            </div>
                            <!--<form name="resumeform" action="processupload.php" onSubmit="return false"  method="post" enctype="multipart/form-data">-->
                            <form name="resumeform"   method="post" enctype="multipart/form-data">
							<div class="usermane">
                            
							<div style="float:left; margin:20px 0;" class="upload">Upload Resume</div><div class="c3">
								<input type="file" name="resumefile" id="resume" />
							</div>
							<div class="clearfix">
							</div>
							<div class="cr_send">
                                <img src="images/ajax-loader.gif" id="loading-img" style="display:none;" alt="Please Wait"/>
								<a href="javascript:void(0);" style="font-style:inherit;color: inherit;" id="sendresumebtn" onclick="return postresume();" >Send</a>
                                <!--<input type="submit"  id="sendresumebtn" value="Send" />-->
							</div>
                            <div id="progressbox" style="display:none;"><div id="progressbar"></div><div id="statustxt">0%</div></div>
							<div id="output" style="display: none;"></div>
                            </div>
                                <input type="hidden" name="Job[job_id]" id="jobid" value="<?php if(isset($_POST['Job']['job_id'])){ echo $_POST['Job']['job_id']; } ?>" />
                                <input type="hidden" name="Job[cat_id]" id="catid" value="<?php if(isset($_POST['Job']['cat_id'])){ echo $_POST['Job']['cat_id']; } ?>" />
                            </form>
						</div>
</div>
                </div>
            
            
		</div>
    </div>
    
    <div class="clearfix"></div>
    <!--=================Body Contain end=======================-->
    </div>
<?php
    require_once("includes/footer.php");
?>
<script lang="javascript">
//<![CDATA[
function postresume()
{
    if(trim(document.getElementById('resume').value)=="")
    {
        alertify.alert("Please select resume...");
        return false;
    }
    document.resumeform.submit();
}

//]]>
</script>
<?php

if($msg_error!="")
{
    ?>
    <script>
        alertify.alert("<?php echo $msg_error; ?>");
    </script>
    <?php
}
?>